package com.tgy.twoDatabase.controller;

import com.tgy.twoDatabase.entity.Sms;
import com.tgy.twoDatabase.service.MsmService;
import com.tgy.twoDatabase.util.RedisNormlUtil;
import com.tgy.twoDatabase.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("/redis")
public class RedisTestController {

    @Autowired(required = false)
    private MsmService msmService;

    @Resource
    private RedisNormlUtil redisNormlUtil;

    @RequestMapping("/add")
    @ResponseBody
    public String add(@RequestBody Sms sms) throws Exception {
//        Map<String, Object> returnMap = msmService.queryById(msm);//查询
//        Object obj = returnMap.get("result");
//        List list = (List<String>)obj;
//        System.out.println("返回list的大小:"+list.size());
//        System.out.println(Thread.currentThread().getName()+"返回map的大小:"+returnMap.size());
        /**
         * 如果返回的数组是空的就证明数据库中没有相应数据，可以进行插入操作
         */


        //todo 设置时间内只允许插入三条数据
        if(RedisUtil.ListOps.lSize("tel"+ sms.getNumber().toString())< 3){
            try{
                //超时时间为60秒
                redisNormlUtil.lSet("tel"+ sms.getNumber().toString(),"1",60);
                msmService.insert(sms);//插入
            }catch (Exception e) {
                RedisUtil.ListOps.lRightPop("tel"+ sms.getNumber().toString());//插入出异常则删除
                throw e;
            }

            System.out.println(Thread.currentThread().getName()+"success");
            return Thread.currentThread().getName()+"success";
        }else{
            System.out.println(Thread.currentThread().getName()+"exists");
            return Thread.currentThread().getName()+"exists";
        }
    }

}
